//
//  GEEditViewController.m
//  GEMemento
//
//  Created by Grass on 15/8/12.
//  Copyright (c) 2015年 OFashioin. All rights reserved.
//

#import "GEEditViewController.h"

#import "GEMemento.h"

@interface GEEditViewController ()

@property (weak, nonatomic) IBOutlet UITextField *titleTF;
@property (weak, nonatomic) IBOutlet UITextField *subTitleTF;
@property (weak, nonatomic) IBOutlet UITextField *contentTF;

@property (nonatomic, strong) GEMemento *memento;

@end

@implementation GEEditViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.memento = [GEMemento unarchiverMemento] ? [GEMemento unarchiverMemento] : [[GEMemento alloc] init];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self reloadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Helper
- (void)reloadData {
    self.titleTF.text = self.memento.title;
    self.subTitleTF.text = self.memento.subTitle;
    self.contentTF.text = self.memento.content;
}

#pragma mark - Action
- (IBAction)handleTapGesRec:(UITapGestureRecognizer *)sender {
    [self.view endEditing:YES];
}

- (IBAction)handleEditingDidEnd:(UITextField *)sender {
    if (sender == self.titleTF) {
        self.memento.title = sender.text;
    } else if (sender == self.subTitleTF) {
        self.memento.subTitle = sender.text;
    } else if (sender == self.contentTF) {
        self.memento.content = sender.text;
    }
    [GEMemento archiverMememnto:self.memento];
}

- (IBAction)didClickSubmit:(UIButton *)sender {
    [self.view endEditing:YES];
    
    [GEMemento clearArchiverMemento];
    self.memento = [GEMemento unarchiverMemento];
    [self reloadData];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
